
import 'dart:convert';

import 'package:data_table_2/data_table_2.dart';
import 'package:flutter/material.dart';
import 'package:shadcn_ui/shadcn_ui.dart';

import '../../eventbus/EventBusUtil.dart';
import '../../eventbus/EventRefreshBase.dart';
import '../../util/BaseRequest.dart';
import '../../util/ColorUtil.dart';
import '../../util/ToastUtil.dart';
import '../../util/ViewUtil.dart';
import '../Controller/MaterialController.dart';
import '../dto/PriceParm.dart';
import '../dto/PricePart.dart';
import '../dto/PriceRule.dart';
import 'ParmVC.dart';
import 'RuleVC.dart';

class MaterialView extends StatefulWidget {
  final MaterialController partController;
  const MaterialView({super.key, required this.partController});

  @override
  State<MaterialView> createState() => _MaterialViewState();
}

class _MaterialViewState extends State<MaterialView> {

  final formKey = GlobalKey<ShadFormState>();
  PricePart pricePart=PricePart();

  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _codeController = TextEditingController();
  final TextEditingController _specController = TextEditingController();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  widget.partController.refreshPricePart=(PricePart part){
    debugPrint('刷新${part.parentId}');
    if(part.parentId !='0'){
      debugPrint('刷新${part.parentId}');
      pricePart=part;
      _nameController.text=pricePart.name;
      _codeController.text=pricePart.code;
      _specController.text=pricePart.spec;
      setState(() {

      });
    }
  };


  }


  @override
  void dispose() {

    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    return  Column(
      children: [
        ShadForm(
          key: formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              ShadInputFormField(
                id: 'name',
                label: const Text('型号名称'),
                controller: _nameController,
                placeholder: const Text('请输入型号名称'),
                validator: (v) {
                  if (v.isEmpty) {
                    return '请输入型号名称';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              ShadInputFormField(
                id: 'code',
                label: const Text('Code'),
                controller: _codeController,
                placeholder: const Text('请输入Code'),
                validator: (v) {
                  if (v.isEmpty) {
                    return '请输入Code';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              ShadInputFormField(
                id: 'price',
                label: const Text('单价'),
                suffix: const Text('元'),
                controller: _codeController,
                placeholder: const Text('请输入单价'),
                validator: (v) {
                  if (v.isEmpty) {
                    return '请输入单价';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              ShadInputFormField(
                id: 'spec',
                label: const Text('型号说明'),
                controller: _specController,
                placeholder: const Text('请输入型号说明'),
                validator: (v) {
                  if (v.isEmpty) {
                    return '请输入型号说明';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [ViewUtil.textButton('保存', ViewUtil.screenWidth(400), ViewUtil.screenHeight(30), ViewUtil.radio(15),
                    ColorUtil.colorBlue, ColorUtil.colorBlue, Colors.white , ViewUtil.fontSize(25), (){
                      submitMaterial();
                    }),],
              ),



            ],

          ),

        ),

        const SizedBox(height: 16),
        Row(
          children: [
            Text('单价计算公式',style: TextStyle(fontSize: ViewUtil.fontSize(28)),),
            SizedBox(width: ViewUtil.screenWidth(10),),
            ViewUtil.textButton('编辑', ViewUtil.screenWidth(20), ViewUtil.screenHeight(10), ViewUtil.radio(15),
                ColorUtil.colorBlue, ColorUtil.colorBlue, Colors.white , ViewUtil.fontSize(25), (){
                  showShadSheet(
                    side: ShadSheetSide.right,
                    context: context,
                    builder: (context) =>  RuleVC(pricePart:pricePart , callback: () {
                      //回调
                    },),
                  );

                }),
          ],
        ),
        Card(
          color: Colors.white,
          child:
        Container(
          padding: EdgeInsets.only(left: 10,right: 10,top: 5,bottom: 5),
          alignment: Alignment.centerLeft,
          child: Text(getRuleString(pricePart.rule),style: TextStyle(fontSize: 20),),
        )),

        const SizedBox(height: 16),
        Row(
          children: [
            Text('参数',style: TextStyle(fontSize: ViewUtil.fontSize(28)),),
            SizedBox(width: ViewUtil.screenWidth(10),),
            ViewUtil.textButton('新增', 10, 5, ViewUtil.radio(15),
                ColorUtil.colorBlue, ColorUtil.colorBlue, Colors.white , ViewUtil.fontSize(25), (){
                  PriceParm priceParm=PriceParm();
                  priceParm.parentId=pricePart.id;
                  showShadSheet(
                    side: ShadSheetSide.right,
                    context: context,
                    builder: (context) =>  ParmVC(
                      pricePart: pricePart,
                      priceParm: priceParm,
                      callback: () {
                      //回调
                    },),
                  );

                }),
          ],
        ),
        ConstrainedBox(constraints: const BoxConstraints(maxHeight: 500 ),
          child:
          DataTable2(
              isHorizontalScrollBarVisible:true,
              columnSpacing: 12,
              horizontalMargin: 12,
              columns: [
                DataColumn2(
                  label: Text('操作'),
                  fixedWidth: 150,
                ),
                DataColumn2(
                  label: Text('参数名称'),
                  size: ColumnSize.L,
                ),
                DataColumn2(
                  label: Text('单位'),
                  fixedWidth: 100,
                ),
                DataColumn2(
                  label: Text('录入方式'),
                  fixedWidth: 100,
                ),
                DataColumn2(
                  label: Text('是否必填'),
                  fixedWidth: 100,
                ),
                DataColumn2(
                  label: Text('录入数据'),
                  size: ColumnSize.L,
                ),

              ],
              rows: getDataRows()

          ),


        )




      ],
    );
  }


  getDataRows(){
    List<DataRow> datas=[];
    for (var item in pricePart.parmList) {
      datas.add(DataRow(cells: [
        DataCell(ViewUtil.textButton('编辑', ViewUtil.screenWidth(20), ViewUtil.screenHeight(10), ViewUtil.radio(15),
            ColorUtil.colorBlue, ColorUtil.colorBlue, Colors.white , ViewUtil.fontSize(25), (){
              showShadSheet(
                side: ShadSheetSide.right,
                context: context,
                builder: (context) =>  ParmVC(
                  pricePart: pricePart,
                  priceParm: item,
                  callback: () {
                    //回调
                  },),
              );

            })),
        DataCell(Text(item.name)),
        DataCell(Text(item.unit)),
        DataCell(Text(item.handle==0?'输入数据':'录入公式')),
        DataCell(Text(item.required==0?'非必填':"必填")),
        DataCell(Text(item.handle==0?item.value:getRuleString(item.rule))),
      ]));


    }
  return datas;
  }


  void submitMaterial(){
    if (formKey.currentState!.saveAndValidate()) {
      var values= formKey.currentState!.value;
      var name=values["name"];
      var code=values["code"];
      var spec=values["spec"];
      var parentId=pricePart.parentId;
      var id=pricePart.id;
      var parm={
        "name":name,
        "code":code,
        "spec":spec,
        "parentId":parentId,
        "id":id,
      };
      BaseRequest.postHttp("price/editmatterial",parameters: parm, canTip: true, context: context, onSuccess: (data){
        bool result=BaseRequest.chekResponse(data, true);
        if(result){
          ToastUtil.showToast("编辑成功");
          eventBus.fire(EventRefreshBase());
        }
      }, onError: (error){

      });
    }
  }

  getRuleString(var rule){
    var ruleStr="";
    if(rule.isNotEmpty){
      List<dynamic> list = json.decode(rule);
       
      for(var item in list){
        PriceRule rule=PriceRule.fromJson(item);
        if(rule.handle==0){
          ruleStr="$ruleStr${rule.value}";
        }else{
          ruleStr="$ruleStr${rule.name}";
        }
      }
    }

    return ruleStr;
  }

}
